#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "tp2.h"

  void  AdicionaSK(PK *add, PK *listaSK, int *nSK, FILE *file, FILE *avail, int tm){
    int navail, i=0, b, NRR=0;
    char titulo[tm], buffer[200], test[200];
    PK *found, aux;
    while((titulo[i]!=' ')&&(i<tm)){
      while((titulo[i]!=' ')&&(i<tm)){
        buffer[i]=titulo[i];
        i++;
      }
      b=i;
      i++;
      while(b<200){
         buffer[b]=' ';
         b++;
      }
      if((*nSK)>0){
        found=BSearch(listaSK,buffer,0,(*nSK)-1);
      }
      else{
        found=NULL;
      }
      if(found==NULL){
        fread(&navail,1,4,avail);
        if(navail==-1){
          while(fgets(test,200,file)!=NULL){
            NRR++;
            fseek(file,NRR*204,0);
          }
          for(b=0;b<200;b++){
            aux.titulo[b]=titulo[b];
          }
          aux.NRR=-1;
          fwrite(&aux,1,sizeof(PK),file);
        }
        else{
          fseek(file,(navail*204)+1,0);
          NRR=navail;
          fread(&navail,1,4,file);
          fseek(avail,0,0);
          fwrite(&navail,1,4,avail);
          fseek(file,NRR*204,0);
          for(b=0;b<200;b++){
            aux.titulo[b]=titulo[b];
          }
          aux.NRR=-1;
          fwrite(&aux,1,sizeof(PK),file);
        }
        if((*nSK)%20==0){
          listaSK=(PK*)realloc(listaSK,((*nSK)+20)*sizeof(PK));
        }
        for(b=0;b<200;b++){
          listaSK[*nSK].titulo[b]=buffer[b];
        }
        listaSK[*nSK].NRR=NRR;
        (*nSK)++;
      }
      else{
        fread(&navail,1,4,avail);
        if(navail==-1){
          while(fgets(test,200,file)!=NULL){
             NRR++;
            fseek(file,NRR*204,0);
          }
          for(b=0;b<200;b++){
            aux.titulo[b]=titulo[b];
          }
          aux.NRR=-1;
          fwrite(&aux,1,sizeof(PK),file);
        }
        else{
          fseek(file,(navail*204)+1,0);
          NRR=navail;
          fread(&navail,1,4,file);
          fseek(avail,0,0);
          fwrite(&navail,1,4,avail);
          fseek(file,NRR*204,0);
          for(b=0;b<200;b++){
            aux.titulo[b]=titulo[b];
          }
          aux.NRR=-1;
          fwrite(&aux,1,sizeof(PK),file);
        }
        if(found->NRR==-1){
          found->NRR=NRR;
        }
        else{
          NRR=found->NRR;
          while(NRR!=-1){
            fseek(file,(NRR*204)+200,0);
            fread(&NRR,1,4,file);
          }
          fseek(file,(NRR*204)+200,0);
          fwrite(&NRR,1,4,file);
        }
      }
    }
  }
